package client.gui;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import net.miginfocom.swing.MigLayout;
import client.core.Car;
import client.core.Client;
import client.core.Engine;
import client.core.Rental;

public class BranchRentedCars extends JPanel {
	private JTextField txtClient;
	private JTextField txtFrom;
	private JTextField txtTo;
	private JList<Car> listRentedCars;
	public BranchRentedCars() {
		setLayout(new MigLayout("", "[][grow]", "[grow][][][]"));
		
		listRentedCars = new JList<Car>();
		listRentedCars.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				if (listRentedCars.getSelectedIndex() == -1)
					return;
				try {
					Engine e = Engine.getInstance();
					updateTextFields(listRentedCars.getSelectedValue().getId());
				} catch (SQLException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		add(new JScrollPane(listRentedCars), "cell 0 0 2 1,grow");
		
		JLabel lblClient = new JLabel("Klient");
		add(lblClient, "cell 0 1,alignx trailing");
		
		txtClient = new JTextField();
		txtClient.setEditable(false);
		add(txtClient, "cell 1 1,growx");
		txtClient.setColumns(10);
		
		JLabel lblFrom = new JLabel("Od");
		add(lblFrom, "cell 0 2,alignx trailing");
		
		txtFrom = new JTextField();
		txtFrom.setEditable(false);
		add(txtFrom, "cell 1 2,growx");
		txtFrom.setColumns(10);
		
		JLabel lblTo = new JLabel("Do");
		add(lblTo, "cell 0 3,alignx trailing");
		
		txtTo = new JTextField();
		txtTo.setEditable(false);
		add(txtTo, "cell 1 3,growx");
		txtTo.setColumns(10);
		
		refreshList();
	}
	
	public void refreshList() {
		try {
			Engine e = Engine.getInstance();
			DefaultListModel<Car> model = new DefaultListModel<>();
			List<Car> rentedCars = e.getRentedCars();
			for (Car c : rentedCars) {
				model.addElement(c);
			}
			listRentedCars.setModel(model);
			listRentedCars.setSelectedIndex(-1);
		} catch (SQLException | IOException e) {
			e.printStackTrace();
		}
	}
	
	private void updateTextFields(int carId) throws SQLException, IOException {
		Engine e = Engine.getInstance();
		Rental rental = e.getRentalByCar(carId);
		Client client = e.getClientById(rental.getClientId());
		txtClient.setText(client.toString());
		txtFrom.setText(rental.getDateFrom().toString());
		txtTo.setText(rental.getDateTo().toString());
	}

}
